/*
 * User: Sepheus Angelus
 * Date: 05/03/2008
 * Time: 09:28
 * 
 */

using System;
using System.Xml;
using System.IO;

namespace Aphyros_MUD_Server
{
	/// <summary>
	/// Reads in the XML settings file.
	/// </summary>
	public class SettingsReader
	{
		private const string SettingsFile = "Settings.xml";
		private static XmlTextReader settingReader;
		
		/// <summary>
		/// Reads the settings from the settings file in XML format.
		/// </summary>
		/// <returns>True if the read is successful.  False if problems are encountered.</returns>
		public static bool Read()
		{
			try
			{
				settingReader = new XmlTextReader(SettingsFile);
			}
			catch
			{
				Console.ForegroundColor = ConsoleColor.Red;
				Console.WriteLine("Unable to read {0}",SettingsFile);
				return false;
			}
			if(!File.Exists(SettingsFile))
			{
				Console.ForegroundColor = ConsoleColor.Red;
				Console.WriteLine("{0} not found.",SettingsFile);
				return false;
			}
			try
			{
				while(settingReader.Read())
				{
					if(settingReader.NodeType == XmlNodeType.Element)
					{
						switch(settingReader.LocalName)
						{
							case "Driver":
								Database.Driver = settingReader.ReadString();
								break;
							case "Server":
								Database.Server = settingReader.ReadString();
								break;
							case "Port":
								Database.Port = settingReader.ReadString();
								break;
							case "Database":
								Database.Schema = settingReader.ReadString();
								break;
							case "UID":
								Database.UID = settingReader.ReadString();
								break;
							case "Password":
								Database.Password = settingReader.ReadString();
								break;
							case "Option":
								Database.Option = settingReader.ReadString();
								break;
							case "ServerPort":
								Program.PortNumber = Convert.ToInt32(settingReader.ReadString());
								break;
							case "Connections":
								Program.BacklogSize = Convert.ToInt32(settingReader.ReadString());
								break;
							case "WorldName":
								Program.WorldName = settingReader.ReadString();
								break;
							default:
								break;
						}
					}
				}
				Console.ForegroundColor = ConsoleColor.Cyan;
				Console.WriteLine("Succeeded in reading settings.");
				settingReader.Close();
				return true;
			}
			catch
			{
				Console.ForegroundColor = ConsoleColor.Red;
				Console.WriteLine("Error in settings.");
				settingReader.Close();
				return false;
			}
		}
	}
}
